require 'Common/define'
require 'Logic/Config'
require 'Common/functions'

UIArenaRecord = {};
HelperFunc.SetUIEnv(UIArenaRecord)
local this = UIArenaRecord;

this.hasInit = false;
this.btnBackButton = nil;
this.listItemGrid = nil;
this.backFunction = nil;
this.nothingController = nil;
--- @type table<number, BattleRecord> 对战记录列表
this.recordList = {};
this.itemCofig = nil;

function UIArenaRecord.Init(cb, _arena_type) -- _arena_type 竞技场类型
    --todo 应该小写 暂时先大写
    backFunction = cb;
    this.cur_arena_type = _arena_type or EnumConst.ArenaBattleType.Normal
    if this.itemCofig == nil then
        this.itemCofig = G.dataTable["t_item"];
    end
    local singleItemConfig = nil
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        singleItemConfig = logicMgr.ItemManager.getItemConstDatabyModelId(CurrencyEnum.ChallengeTicket)
    elseif  this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        singleItemConfig = logicMgr.ItemManager.getItemConstDatabyModelId(CurrencyEnum.CrossChallengeTicket)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        singleItemConfig = logicMgr.ItemManager.getItemConstDatabyModelId(CurrencyEnum.CrossTeamChallengeTicket)
    end
    this.cost_img_url = "ui://ItemAtlas/" .. singleItemConfig["icon"]

    local name, packageName = getUIName(PanelResNames.UIArenaRecord)
    panelMgr:Push(name, packageName, this.onCreate, Config.useLocalUI)
end

function UIArenaRecord.onCreate(obj)

    if not hasInit then
        hasInit = true;
        btnBackButton = obj:GetChild("bg")
        this.tips = obj:GetChild("tips")
        this.tips.text = getLanguage("ArenaHLTips8")
        bgClose =  obj:GetChild("bgClose")
        listItemGrid = obj:GetChild("itemList")
        local itemList2 = obj:GetChild("itemList2")
        listItemGrid2 = itemList2:GetChild("itemList2")
        nothingController = obj:GetController("nothing")
        this.ctrl_type = obj:GetController("type")
        this.addEvent()
    end
    this.LocalListenEvent()

    this.ctrl_type:SetSelectedIndex(0)
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        logicMgr.ArenaManager.requestRecordInfo(false)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        logicMgr.ArenaManager.requestCrossRecordInfo(false)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        logicMgr.ArenaManager.requestCrossTeamRecordInfo(false)
        this.ctrl_type:SetSelectedIndex(1)
    else
        error("错误竞技场类型")
    end
    
    this.refreshWithData()
end

function UIArenaRecord.addEvent()
    btnBackButton.onClick:Add(this.onClickBack)
    bgClose.onClick:Add(this.onClickBack)
end

function UIArenaRecord.removeEvent()
    btnBackButton.onClick:Remove(this.onClickBack)
    bgClose.onClick:Remove(this.onClickBack)
end

function UIArenaRecord.LocalListenEvent()
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        ListenEvent(Config.EventType.Fresh_ArenaRecords, this.refreshWithData)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        ListenEvent(Config.EventType.Fresh_CrossArenaRecords, this.refreshWithData)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        ListenEvent(Config.EventType.Fresh_CrossTeamArenaRecords, this.refreshWithData)
    else
        error("错误竞技场类型")
    end
end

function UIArenaRecord.LocalCloseEvent()
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        CloseEvent(Config.EventType.Fresh_ArenaRecords, this.refreshWithData)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        CloseEvent(Config.EventType.Fresh_CrossArenaRecords, this.refreshWithData)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        CloseEvent(Config.EventType.Fresh_CrossTeamArenaRecords, this.refreshWithData)
    else
        error("错误竞技场类型")
    end
    
end

function UIArenaRecord.OnDestroy()
    this.removeEvent()
    this.itemCofig = nil
    if this.effect_mat then
        this.effect_mat:SetFloat("_StencilComp", 8)
        this.effect_mat = nil
    end

    if this.effect_mat2 then
        this.effect_mat2:SetFloat("_StencilComp", 8)
        this.effect_mat2 = nil
    end
end

-- function UIArenaRecord.OnEnable()
--     this.LocalListenEvent();
-- end

function UIArenaRecord.OnDisable()
    this.LocalCloseEvent();
    if this.effect_mat then
        this.effect_mat:SetFloat("_StencilComp", 8)
    end

    if this.effect_mat2 then
        this.effect_mat2:SetFloat("_StencilComp", 8)
    end
    this.effect_mat2 = nil
    this.effect_mat = nil
end

function UIArenaRecord.refreshWithData()
    this.recordList = {}
    this.tips.visible = false;
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        this.recordList = logicMgr.ArenaManager.getRecords()
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        this.recordList = logicMgr.ArenaManager.getCrossRecords()
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        this.tips.visible = true;
        this.recordList = logicMgr.ArenaManager.getCrossTeamRecords()
    end
    --print("=====对战记录=====>" .. #this.recordList)
    if this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        listItemGrid2.itemRenderer = this.setData2
        local num = #this.recordList
        if #this.recordList >= 12 then num = 12 end
        listItemGrid2.numItems = num
    else
        listItemGrid.itemRenderer = this.setData
        local num = #this.recordList
        if #this.recordList >= 12 then num = 12 end
        listItemGrid.numItems = num
    end
    if #this.recordList <= 0 then
        this.nothingController:SetSelectedIndex( 1 )
    else
        this.nothingController:SetSelectedIndex( 0 )
    end
end
 
function UIArenaRecord.setData2(index, obj)
    local data = this.recordList[index + 1]
    local txt_time = obj:GetChild("Time")
    local txt_name = obj:GetChild("Name")
    local head_player = obj:GetChild("headPlayer")
    local txt_score = obj:GetChild("Score")
    local btn_record = obj:GetChild("RecordBtn")
    btn_record.onClick:Clear()
    local icon_level = obj:GetChild("Icon")
    local ctrl_if_win = obj:GetController("ifWin")
    local img_level = obj:GetChild("Effect_Dwsg")
    local txt_level_name = obj:GetChild("Rank")
    if data ~= nil then
        if this.effect_mat == nil then
            local t = img_level.displayObject.cachedTransform:Find("GoWrapper/effect_dwsg_SkeletonData")
            if t ~= nil then
                local anim = t:GetComponent("SkeletonAnimation")
                this.effect_mat = Util.GetMaterialOnSkeletonAnimation(anim, "effect_dwsg_Material")
                if this.effect_mat then
                    this.effect_mat:SetFloat("_StencilComp", 3)
                end 
                this.effect_mat2 = Util.GetMaterialOnSkeletonAnimation(anim, "effect_dwsg_Material-Additive")
                if this.effect_mat2 then
                    this.effect_mat2:SetFloat("_StencilComp", 3)
                end
            end
        end 

        local isMeAttack = false;
        local attacker = data.records[1].attacker 
        if tostring(attacker.playerId) == tostring(logicMgr.HeroManager.GetRoleInfo().playerId) then
            attacker = data.records[1].defender
            isMeAttack = true;
        end
        if (this.IsWin(data) and isMeAttack) or (not this.IsWin(data) and not isMeAttack) then
            ctrl_if_win:SetSelectedIndex(0)
        else
            ctrl_if_win:SetSelectedIndex(1)
        end

        txt_name.text = attacker.playerName
        txt_score.text = getNumString(  this.GetPowers( data ) )
        --head_player:GetChild("head"):GetChild("HeadIcon").url = EnumConst.AtlasPath.ICONAtlas .. dataTable.getRow("t_hero", attacker.pic)["f_HeroIcon"]
        --head_player:GetChild("frame").url = EnumConst.AtlasPath.ICONAtlas .. attacker.picFrame
        UIComponentInterface:SetPlayerIcon(head_player:GetChild("head"):GetChild("HeadIcon"), attacker.pic, head_player:GetChild("frame"), attacker.picFrame)
        local cfg_grading, cfg_matching = ArenaManager.getAthleticGradingConfigByRank(tonumber(tostring(attacker.score)))
        icon_level.url = EnumConst.AtlasPath.ICONAtlas .. cfg_grading.f_Icon
        txt_level_name.text = getLanguage(cfg_matching.f_RankName)
        txt_time.text = getTimeStrType2(tonumber(tostring(data.records[1].createTime) ))
        btn_record.onClick:Add( function() showUI(PanelNames.UIRecord, clone(data.records) ) end )
        local level = cfg_grading.f_RankId
        img_level.animationName = "idle" .. level
        img_level.skinName = level
        img_level.loop = true
    end
end

function UIArenaRecord.GetPowers( data )
    local power = 0
    if data ~= nil then
        for _, v in ipairs(data.records) do
            if v ~= nil then
                power = power + tonumber(tostring(v.attacker.power))
            end
        end 
    end
    return power
end
function UIArenaRecord.IsWin( data )
    local win_count = 0
    if data ~= nil then
        for _, v in ipairs(data.records) do
            if v and v.win == 1 then
                win_count = win_count + 1
            end
        end
        if win_count >= 2 then
            return true
        end
    end
    return false
end
function UIArenaRecord.setData(index, obj)
    local data = this.recordList[index + 1]

    local server_name_controller = obj:GetController("ServerName")
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        server_name_controller:SetSelectedIndex(0)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        server_name_controller:SetSelectedIndex(1)
        local txt_server_name = obj:GetChild("textSevers")
        local sever_data = logicMgr.LoginManager.GetServerInAll(data.serverId or 0)
        if sever_data ~= nil then
            txt_server_name.text = sever_data[Server_ENU_INDEX.NAME] 
        else
            txt_server_name.text = "未知"
        end
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        server_name_controller:SetSelectedIndex(1)
        local txt_server_name = obj:GetChild("textSevers")
        local sever_data = logicMgr.LoginManager.GetServerInAll(data.serverId or 0)
        if sever_data ~= nil then
            txt_server_name.text = sever_data[Server_ENU_INDEX.NAME] 
        else
            txt_server_name.text = "未知"
        end
    else
        error("错误竞技场类型")
    end

    local itemCtr = CtrlManager.GetCtrl(PanelNames.ArenaRecordItem)
    itemCtr.initData(obj, data, this.cur_arena_type)
    local battleBtn = obj:GetChild("Button");
    if data.backFight ~= 0 then
        battleBtn.visible = false
    end
    local cost_icon = battleBtn:GetChild("icon")
    cost_icon.url = this.cost_img_url
    battleBtn.onClick:Clear();
    battleBtn.onClick:Add(function()
        this.onClickItemChallenge(data);
    end)

    local recordBtn = obj:GetChild("RecordBtn");
    recordBtn.onClick:Clear();
    recordBtn.onClick:Add(function()
        this.onClickItemRecord(data);
    end)

    local shareBtn = obj:GetChild("ShareBtn");
    shareBtn.onClick:Clear();
    shareBtn.onClick:Add(function()
        this.onClickItemShare(data);
    end)
end

function UIArenaRecord.onClickBack()
    closeUI(PanelNames.UIArenaRecord);
    if backFunction ~= nil then
        backFunction();
    end
end

--- 挑战点击事件
--- @param data BattleRecord 对战记录
function UIArenaRecord.onClickItemChallenge(data)
    
    local is_enough = false
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        local baseInfo = logicMgr.ArenaManager.getBaseInfo();
        if baseInfo.times < baseInfo.freeTimes or logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.ChallengeTicket) > 0 then
            is_enough = true
        end
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        local infoChallengeTicketNum = logicMgr.ItemManager.getItemCountbyItemTypeAndItemModelId(EnumConst.ItemTableEnum.Item, CurrencyEnum.CrossChallengeTicket) or 0  
        local arenaCrossBaseInfo = logicMgr.ArenaManager.getCrossBaseInfo() 
        if (arenaCrossBaseInfo.times < arenaCrossBaseInfo.freeTimes) or infoChallengeTicketNum > 0 then
            is_enough = true
        end 
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then
        local baseInfo = logicMgr.ArenaManager.getCrossTeamBaseInfo()
        if baseInfo.times < baseInfo.freeTimes or logicMgr.ItemManager.getCurrencyCountByModelId(CurrencyEnum.CrossTeamChallengeTicket) > 0 then
            is_enough = true
        end
    else
        error("错误竞技场类型")
    end

    if is_enough then
        local myPlayerId = G.serverData["roleInfo"].show.playerId;
        local fighter = tostring(data.attacker.playerId) == tostring(myPlayerId) and data.defender or data.attacker;
        local local_arena_type = this.cur_arena_type
        local param = {}
        param.power = fighter.power;
        param.id = fighter.playerId;
        param.arena_type = cur_arena_type
        if local_arena_type == EnumConst.ArenaBattleType.Normal then
            param.type = EnumConst.FormationType.ArenaAtk
        elseif local_arena_type == EnumConst.ArenaBattleType.Cross then
            param.type = EnumConst.FormationType.CrossArenaAtk
        elseif local_arena_type== EnumConst.ArenaBattleType.TeamCross then
            param.type = EnumConst.FormationType.TeamCrossArenaAtk
        else
            error("错误竞技场类型")
        end
        showUI(PanelNames.UIBattleTeam, EnumConst.FightTypeConst.ARENARECORD, param, function(formations)
            FightManager.SetRePlay(false)
            if local_arena_type == EnumConst.ArenaBattleType.Normal then
                arenaHandler.sendArenaBattle(fighter.playerId, data.robot, formations[1], data.fightId)
            elseif local_arena_type == EnumConst.ArenaBattleType.Cross then
                crossArenaHandler.sendCrossArenaBattle(fighter.playerId, data.robot, formations[1], data.fightId)
            elseif local_arena_type ==  EnumConst.ArenaBattleType.TeamCross  then
                crossTeamArenaHandler.sendReqHighArenaBattle(fighter.playerId, data.robot, formations, data.fightId)
            end
            
        end)
        UIArenaRecord.onClickBack()
    else
        UISysTips.AddMsg(getLanguage("ErrorCode_3526"));
    end
end

--- 记录点击事件
--- @param data BattleRecord 对战记录
function UIArenaRecord.onClickItemRecord(data)
    local local_arena_type = this.cur_arena_type
    local formation_type = nil
    if local_arena_type == EnumConst.ArenaBattleType.Normal then
        formation_type = EnumConst.FormationType.ArenaAtk
    elseif local_arena_type == EnumConst.ArenaBattleType.Cross then
        formation_type = EnumConst.FormationType.CrossArenaAtk
    elseif local_arena_type == EnumConst.ArenaBattleType.TeamCross then
        formation_type = EnumConst.FormationType.TeamCrossArenaAtk
    else
        error("错误竞技场类型")
    end
    showUI(PanelNames.UILevelRecode, EnumConst.FightTypeConst.ARENA, data, nil, function() 
        showUI(PanelNames.UIArenaRecord, function()  
            showUI(PanelNames.UIArenaMain, local_arena_type)
            UIArenaMain.typeCtrl.selectedPage = 0;
            FightManager.SetRePlay(false)
        end, local_arena_type)
        
        if not isOpenUI(PanelNames.UIArenaMainEnter) then
            showUI(PanelNames.UIArenaMainEnter)
        end
    end, nil, formation_type)
end

--- 分享点击事件
--- @param data BattleRecord 对战记录
function UIArenaRecord.onClickItemShare(data)
    
    if this.cur_arena_type == EnumConst.ArenaBattleType.Normal then
        logicMgr.ArenaManager.sendAddSpecialBattle(data.fightId)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.Cross then
        logicMgr.ArenaManager.sendCrossAddSpecialBattle(data.fightId)
    elseif this.cur_arena_type == EnumConst.ArenaBattleType.TeamCross then 
        logicMgr.ArenaManager.sendCrossTeamAddSpecialBattle(data.fightId)
    else
        error("错误竞技场类型")
    end
end

return UIArenaRecord;
